<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'device:inMeasuringEquipment:buttonEdit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
    destroyOnClose="true"
    @close="handleDrawerClose"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" ref="formRef" :key="formTimeKey" />
    <div class="fireVeIm">
      <div class="fireImg">
        <span>
          示例图:
        </span>
        <Image v-if="imageFire" :src="imageFire" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" style="width: 150px;height:auto;" alt="">
      </div>
    </div>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsDeviceManagementInMeasuringEquipmentForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {Office, officeTreeData,officeListData,officeTreeDataList} from '/@/api/sys/office';
  import { InMeasuringEquipment, inMeasuringEquipmentSave, inMeasuringEquipmentForm } from '/@/api/device.management/inMeasuringEquipment';
  import { unitBuildingListData } from '/@/api/unitmanage/unitBuilding';
  import { unitEnterpriseDominantListData } from '/@/api/unitmanage/unitEnterpriseDominant';
  import { unitRegionListData } from '/@/api/unitmanage/unitRegion';
  import { Image } from 'ant-design-vue'
  
  let inMeasuringEquipment_file = ref<any>();

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('device.management.inMeasuringEquipment');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<InMeasuringEquipment>({} as InMeasuringEquipment);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增前端采集设备') : t('编辑前端采集设备'),
  }));
  const imageFire=ref()

    // 响应式获取enterpriseCode
  const TaskEenterpriseCode=ref()
  const ResTaskEenterpriseCode=ref()
  const regionParams=computed(()=>{
    const enterpriseId=TaskEenterpriseCode.value?TaskEenterpriseCode.value:ResTaskEenterpriseCode.value
    console.log('regionParams.enterpriseId',enterpriseId)
    return enterpriseId
  })
  console.log('regionParams',regionParams)

  const EnterpriseParams = ref<Recordable>({
     name:''
  });

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('企业名称'),
      field: 'enterpriseId',
      fieldLabel:'enterpriseName',
      component: 'Select',
      componentProps: () => {
        return {
          api: unitEnterpriseDominantListData,
          params: EnterpriseParams.value,
          fieldNames: { label: 'name', value: 'unitCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            EnterpriseParams.value.name = value;
            console.log(EnterpriseParams.value);
          },
          onChange:(unitCode)=>{
            TaskEenterpriseCode.value=unitCode
            console.log(unitCode)
          }
        };
      },
      required: true,
    },
    {
      label: t('设备名称'),
      field: 'equipmentName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('设备类型'),
      field: 'equipmentType',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        dictType: 'testing_equipment_type',
      },
      required: true,
    },
    {
      label: t('所属建筑'),
      field: 'buildId',
      fieldLabel:'buildName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitBuildingListData,
        resultField: 'list',
         key:"formTimeKey",
        params:{
        unitCode:regionParams
      },
        fieldNames:{
          label:'name',
          value:'id'
        }

      },
      required: true,
    },
    {
      label: t('监测阈值-最小值'),
      field: 'thresholdValue',
      component: 'Input',
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('监测阈值-最大值'),
      field: 'thremaxValue',
      component: 'Input',
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('设备IMEI'),
      field: 'imei',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    // {
    //   label: t('安装建筑ID'),
    //   field: 'buildId',
    //   component: 'Input',
    //   rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    // },
    {
      label: t('楼层'),
      field: 'floorNum',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    // {
    //   label: t('区域ID'),
    //   field: 'regionId',
    //   component: 'Input',
    //   rules: [{ required: true }, { pattern: /^\d+$/, message: t('请输入一个正整数') }],
    // },
    {
      label: t('区域名称'),
      field: 'regionId',
      fieldLabel:'regionName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitRegionListData,
        key:"formTimeKey",
        resultField: 'list',
        params:{
        enterpriseId:regionParams
      },
        onChange:(id,name)=>{
          record.value.regionId= id
          // record.value.regionName= name
        },
        fieldNames:{
          label:'name',
          value:'id'
        }
      },
      required: true,
    },
    {
      label: t('详细地址'),
      field: 'address',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('监测类型'),
      field: 'pressureType',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        options:[
          {label:'喷淋泵压力', value:'01'},
          {label:'消火栓泵压力', value:'消火栓泵压力'},
          {label:'最不利点消火栓压力', value:'20'},
          {label:'喷淋管网压力', value:'30'}
        ]
      },
    },
    {
      label: t('检测间隔'),
      field: 'jctime',
      component: 'Input',
      rules: [{ pattern: /^\d+$/, message: t('请输入一个正整数') }],
    },
    {
      label: t('卡号'),
      field: 'cardCode',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
    },
    {
      label: t('示例图'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        fileUrl:computed(() => record.value.fileUrl),
        bizType: 'inMeasuringEquipment_file',
        uploadType: 'all',
        maxNumber:1,
      },
    }
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await inMeasuringEquipmentForm(data);
    ResTaskEenterpriseCode.value=res.inMeasuringEquipment.enterpriseId
    imageFire.value=res.inMeasuringEquipment.image
    record.value = (res.inMeasuringEquipment || {}) as InMeasuringEquipment;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

const formRef = ref<any>();
const formTimeKey=ref(Date.now());
const handleDrawerClose = () => {
  formRef.value.resetFields();
  TaskEenterpriseCode.value=undefined;
}


  async function handleSubmit() {
    try {
      let data = await validate();
      data={
        ...data,
        image:(data.dataMap.inMeasuringEquipment_fileUrl != null) ? (data.dataMap.inMeasuringEquipment_fileUrl.split('?')[0]) : record.value.image, 
      }
   
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
        // enterpriseId: record.value.enterpriseId,
        // buildId: record.value.buildId,
        // regionId: record.value.regionId,
        
      };
      // console.log('submit', params, data, record);
      const res = await inMeasuringEquipmentSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
<style scoped lang="less"> 
.fireVeIm{
  display: flex;
  justify-content: space-start;
  align-items: center;
  margin-bottom: 5%;
  margin-left: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
</style>
